﻿//Copyright (C) <2013>  <jonathan cleeve norton> All Rights Reserved 
//Contact jon.norton@fin-plus.co.uk website <http://www.fin-plus.co.uk/>
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using FinPlusCommon;
using log = Logger.Logger;
using u = FinPlusUtility.Utility;

namespace FinPlusWPFControls
{
    public partial class FinPlusTabItem : TabItem
    {
        public string Id { get { return _id == null ? "ItemTab" : _id; } set { _id = value; } }
        public string[] States { get { return new string[] {  }; } }
        public string[] TestStates { get { return new string[] {  }; } }
        public IFunctions Adaptor { get { return _app.Adaptor; } }
        public string TestString { get { return Adaptor.ToString(); } }
        public bool IsValid { get; set; }
        public string ContainerId { get; set; }

        private const string XmlNode = "root/current";
        private enum DockControls { FinPlusControl, Default }
        private FinPlusControl _app;
        private IFunction _func;
        private string _id;
        private readonly string _user, _configPath, _name;

        public event EventHandler TabClosed;

        //construct
        public FinPlusTabItem(string configPath, string name)
        {
            InitializeComponent();
            _id = _name = name;
            _configPath = configPath;
            _user = Environment.UserName;
            Cursor = ((TextBlock)this.Resources["CPoint"]).Cursor;
        }

        //common control interface
        public void Dock(object control, string dock) { }

        public virtual void CmdRouter(string command)
        {
            CmdExecute(new Function(command, _id, _user));
        }

        public void CmdExecute(IFunction command)
        {
            try
            {
                if (_app != null)
                    _app.CmdCapture(command);

                switch ((Cmds)Enum.Parse(typeof(Cmds), command.Name, true))
                {
                    case Cmds.Open: Open(); break;
                    case Cmds.Save: Save(); break;
                    case Cmds.Close: Close(); break;
                    default: throw new Exception(string.Format("event not recognised {0}", command.Name));
                }
            }
            catch (CmdExecuteException e)
            {
                IsValid = log.Log(Logger.Level.Error, e.Message, e);
            }
        }

        public void Dispose()
        {
            if (_app != null)
                _app.Dispose();
        }

        //public
        public void ShowButtons(bool show)
        {
            controlButtons.Visibility = show ? Visibility.Visible: Visibility.Collapsed;
        }

        //private
        private void Open()
        {
            try
            {
                u.Env env;
                var config = u.ConfigXml(_configPath + ".config", out env);
                Content = _app = new FinPlusView(_configPath, titleText.Text = _name, string.Empty, env);

                _func = new Function("FinPlusTabItem", "finPlusTabItem", Environment.UserName) { Object = finPlusTabItem };
                FinPlusDInject.Get.InjectStates(_func, new Functions(_configPath + "web.state", XmlNode));
            }
            catch (Exception e)
            {
                log.Log(Logger.Level.Warning, e.Message, e);
            }
        }

        private bool Save()
        {
            var funcsState = FinPlusDInject.Get.ExtractStates(_func, Environment.UserName);
            funcsState.ToXmlDoc(XmlNode).Save(_configPath + "web.state");
            return true;
        }

        private void Close()
        {
            try
            {
                if (TabClosed != null)
                    TabClosed.Invoke(Id, new EventArgs());

                Dispose();
            }
            catch (Exception e)
            {
                log.Log(Logger.Level.Error, Id, Id, e.Message, e);
            }
        }

        //cmds
        private enum Cmds { Open, Save, Close }

        //events
        private void Tab_OnClose(object s, RoutedEventArgs a) { CmdRouter(Cmds.Close.ToString()); }
        private void Tab_OnSave(object s, RoutedEventArgs a) { CmdRouter(Cmds.Save.ToString()); }
        private void Tab_OnLoad(object s, RoutedEventArgs a) { CmdRouter(Cmds.Open.ToString()); }
        private void Key_Click(object s, KeyEventArgs a) { if (a.Key == Key.S && Keyboard.Modifiers == ModifierKeys.Control) Tab_OnSave(s, a); }
    }
}
